const express = require('express');
const router = express.Router();
const query = require("../util/db.js")
const R = require("../util/resultJson.js")

router.get("/",function (req,res) {
    res.render("apply/apply-list")
})


router.post("/apply",function (req,res) {
    const {goodsId,count,type} = req.body;
    const userId = req.loginInfo.id;
    let sql = "select * from apply where user_id = ? and goods_id = ? and type = ? and status = 1";
    query(sql,[userId,goodsId,type]).then(list=>{
        if(list.length>0){
            res.json(R.error("请勿重复申请！"))
        }else{
            sql = "insert into apply values (null,?,?,?,?,?,?)";
            query(sql,[userId,goodsId,count,type,new Date(),1]).then(()=>{
                res.json(R.success());
            })
        }
    })
})

router.get("/page",function (req,res) {
    const {page,limit,goodsId,type,status,applyTime} = req.query;
    const userId = req.loginInfo.role === 3?req.loginInfo.id:req.query.userId;
    let sql = "select a.*,u.username uname,g.name gname,g.count gcount from apply a left join userinfo u on a.user_id = u.id left join goods g on a.goods_id = g.id where 1 = 1 ";
    const objs = [];
    if(goodsId){
        sql+="and a.goods_id = ? ";
        objs.push(goodsId);
    }
    if(userId){
        sql+="and a.user_id = ? ";
        objs.push(userId);
    }
    if(type){
        sql+="and a.type = ? ";
        objs.push(type);
    }
    if(status){
        sql+="and a.status = ? ";
        objs.push(status)
    }
    if(applyTime){
        const atr = applyTime.split(" - ");
        sql+="and a.apply_time between ? and ? ";
        objs.push(atr[0]);
        objs.push(atr[1]);
    }
    query(sql,objs).then(list=>{
        const count = list.length;
        sql+="order by a.id desc limit ?,?";
        objs.push((page-1)*limit);
        objs.push(parseInt(limit));
        query(sql,objs).then(applyList=>{
            res.json(R.page(count,applyList));
        })
    })
})

router.delete("/delete/:id",function (req,res){
    let sql = "delete from apply where id = ?";
    query(sql,[req.params.id]).then(()=>{
        res.json(R.success());
    })
})

module.exports = router;
